<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 830px">
        <div class="card-content mt-3">
          <a-form layout="inline" class="mb-5" :model="searchForm" ref="searchFormRef">
            <a-form-item label="收费期" name="year">
              <a-date-picker v-model:value="searchForm.year" style="width: 130px" picker="year" format="YYYY" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onSearch" :icon="h(SearchOutlined)">搜索</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onReset">重置</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(CloudUploadOutlined)" @click="exportVillage">批量导出</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(HistoryOutlined)" @click="onHistory">导出历史</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(CloudDownloadOutlined)" @click="visible = true">批量导入</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(HistoryOutlined)" @click="importHistory = true">导入历史</a-button>
            </a-form-item>
          </a-form>
          <a-table size="middle" :columns="columns" :data-source="tableData" rowKey="areaID" :row-class-name="(_record: any, index: number) =>
              index % 2 === 1 ? 'table-striped' : null
            " :scroll="{ y: 490 }" :pagination="pagination" bordered :loading="loading"
            style="width: 1350px; height: 560px">
          </a-table>
        </div>
      </a-card>
    </div>
    <a-modal :visible="isHistory" title="导出历史" :footer="null" width="1200px" @cancel="isHistory = false">
      <a-table :columns="historyColumns" :data-source="historyDataSource" bordered :pagination="historyPagination"
        class="mt-3" :row-class-name="(_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
          " :scroll="{ y: 490 }">
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'">完成</a-tag>
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
    <a-modal :visible="visible" @cancel="visible = false">
      <div>
        <div>
          <span>1.下载批量导入模版</span>
          <a-divider />
        </div>
        <div class="mb-5">
          <div>
            <span>根据提示信息完善表格内容</span>
          </div>
          <a-button type="primary" :icon="h(DownloadOutlined)" class="mt-3"
            @click="downloadTemplate">包干小区收费导入模板.xls</a-button>
        </div>
        <div>
          <span>2.导入开关栓状态导入模版</span>
          <a-divider />
        </div>
        <a-upload-dragger v-model="fileList" name="file" :multiple="true"
          action="/api/ChargeSystem/SFGL/importHeatingState" :headers="header" @change="handleChange" @drop="handleDrop"
          :beforeUpload="beforeUpload" accept=".xls,.xlsx,.et" class="mt-3">
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">点击/拖拽文件上传</p>
          <p class="ant-upload-hint">
            请将填写好的文件拖拽至此，或点击选择文件
          </p>
          <p class="ant-upload-hint">
            (仅支持.xls、.xlsx、.et格式文件，文件大小限制2MB以内)
          </p>
        </a-upload-dragger>
      </div>
    </a-modal>
    <a-modal :visible="importHistory" @cancel="importHistory = false" title="导入历史" width="1200px">
      <a-form layout="inline">
        <a-form-item label="操作人">
          <a-tree-select v-model:value="searchForm.userId" tree-data-simple-mode allow-clear style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="selectList" placeholder="请选择修改人"
            :load-data="onLoadData" /></a-form-item>
        <a-form-item label="机构">
          <a-tree-select v-model:value="searchForm.comId" tree-node-filter-prop="label" style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="comanyList"
            placeholder="请选择归属机构" /></a-form-item>
        <a-form-item label="文件名">
          <a-input v-model:value="searchForm.fileName" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="导入日期">
          <a-date-picker v-model:value="searchForm.operateDateoperateDate" /></a-form-item>
        <a-form-item>
          <a-button type="primary" @click="search">查询</a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="historyColumns_2" :data-source="historyDataSource_2" bordered :pagination="historyPagination_2"
        class="mt-3" :row-class-name="(_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
          " :scroll="{ y: 490 }">
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'">完成</a-tag>
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, watch } from 'vue';
import {
  SearchOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
  HistoryOutlined,
  DownloadOutlined,
} from '@ant-design/icons-vue';
import {
  getChargeStandardListApi,
  generateHeatFeeApi,
  searchHeatFeeApi,
  deleteHeatFeeApi,
  deleteHeatFeeByQueryApi,
  searchHeatFee2Api,
  getVillageExportHistoryApi,
  getVillageApi,
  getVillageImportHistoryApi,
  exportVillageApi,
} from '#/api/core/charge';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { useAccessStore } from '@vben/stores';
import { getCompanyTree } from '#/api/core/develop';
import { getOperatorApi } from '#/api/core/statistical';

const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const visible = ref(false);
const isHistory = ref(false);
const importHistory = ref(false);
const searchFormRef = ref<any>(null);
const loading = ref(false);
const searchForm = reactive({
  year: '',
  userId: '',
  fileName: '',
  operateDate: '',
});
const chargeStandardList = ref<any[]>([]);
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '用户编号',
    dataIndex: 'villageCode',
    key: 'villageCode',
    align: 'center',
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
  },
  {
    title: '公司',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '支付方式',
    dataIndex: 'payWay',
    key: 'payWay',
    align: 'center',
  },
  {
    title: '支付类型',
    dataIndex: 'paytype',
    key: 'paytype',
    align: 'center',
  },
  {
    title: '实收缴费金额',
    dataIndex: 'realPayAmount',
    key: 'realPayAmount',
    align: 'center',
  },
  {
    title: '实收收费面积',
    dataIndex: 'realPayArea',
    key: 'realPayArea',
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
  },
];
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operationDate',
    key: 'operationDate',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'states',
    key: 'states',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const historyColumns_2 = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'applicationTime',
    key: 'applicationTime',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'approvalTime',
    key: 'approvalTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'applicantName',
    key: 'applicantName',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'states',
    key: 'states',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const historyDataSource = ref([]);
const historyDataSource_2 = ref([]);
const tableData = ref<any[]>([]);
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const historyPagination_2 = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    search();
  },
});
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  } else {
    loading.value = true;
    const data = {
      year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
      treeData: props.selectedNodeId,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    getVillageApi(data).then((res: any) => {
      console.log(res);
      tableData.value = res.data.data.data;
      pagination.total = res.data.data.total;
      loading.value = false;
    });
  }

};
const onReset = () => {
  console.log(searchForm);
  searchFormRef.value.resetFields();
};
const onHistory = () => {
  isHistory.value = true;
  getVillageExportHistoryApi(
    historyPagination.current,
    historyPagination.pageSize,
    10,
  ).then((res: any) => {
    console.log(res);
    historyDataSource.value = res.data.data.data;
    historyPagination.total = res.data.data.total;
  });
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
const fileList = ref([]);
const accessStore = useAccessStore();
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
const downloadTemplate = () => {
  // 从public目录下下载文件
  // window.location.href = '/public/开关栓状态导入模版.xls';
  const templatePath = '/Execl/包干小区收费导入模板.xls';
  const link = document.createElement('a');
  link.href = templatePath;
  link.download = templatePath.split('/').pop() || '';
  document.body.append(link);
  link.click();
  link.remove();
};

const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type ===
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    message.error('只能上传 .xls, .xlsx, .et 格式的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('文件大小不能超过 2MB!');
  }
  return isExcel && isLt2M;
};

const handleChange = (info: any) => {
  if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 200) {
      message.success(`${info.file.name} 文件上传成功`);
    } else {
      message.error(
        `${info.file.name} 文件上传失败: ${info.file.response ? info.file.response.message : '未知错误'}`,
      );
    }
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};
const handleDrop = (e: DragEvent) => {
  console.log(e);
};
const comanyList = ref([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
getTableData();
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const selectList = ref([]);
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const search = () => {
  const query = {
    page: historyPagination_2.current,
    limit: historyPagination_2.pageSize,
    year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
    treeData: props.selectedNodeId,
  };
  getVillageImportHistoryApi(query).then((res: any) => {
    historyDataSource_2.value = res.data.data.data;
    historyPagination_2.total = res.data.data.total;
  });
};
const exportVillage = () => {
  exportVillageApi({
    year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
    treeData: props.selectedNodeId,
  }).then((res: any) => {
    console.log(res);
    if (res.data.data.code == 200) {
      message.success('导出成功');
    } else {
      message.error('导出失败');
    }
  });
};
</script>
<style scoped>
:deep(.ant-card-body) {
  height: 100%;
}

.card-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
